package cn.willbj.brief.rt.util.concurrent.CompletableFuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 【对象方法】
 * TODO
 * runAfterEither 方法
 * 两个CompletionStage，任何一个完成了都会执行下一步的操作（Runnable）
 *
 * runAfterBoth
 * 两个CompletionStage，都完成了计算才会执行下一步的操作（Runnable）
 *
 * thenCompose 方法
 * thenCompose 方法允许你对两个 CompletionStage 进行流水线操作，第一个操作完成时，将其结果作为参数传递给第二个操作。
 *
 * 【静态方法】
 *
 * java.util.concurrent.CompletableFuture#completedFuture(java.lang.Object)
 * supplyAsync
 * runAsync
 * allOf
 * anyOf
 *
 * 链接：https://www.jianshu.com/p/6bac52527ca4
 * @date 2020/12/1
 */
public class DemoOther {

    private static final ExecutorService es = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()*2);

    public static void main(String[] args) throws Exception {
        DemoOther.test01();
    }

    /**
     * 执行顺序:(acceptEither方法，主体哪个执行快，参数是哪个)没有返回值
     * pool-1-thread-1 : num1
     * 我是pool-1-thread-3 : return_value01
     * pool-1-thread-2 : num2
     */
    public static void test01()throws Exception{
        CompletableFuture<String> future01 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " : num1");
            return "return_value01";
        }, es);

        CompletableFuture<String> future02 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(2000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " : num2");
            return "return_value02";
        }, es);


        // x参数为future01和future02的，执行比较快的业务结果
        CompletableFuture<Void> future = CompletableFuture.allOf(future01, future02);

        // Exception in thread "main" java.util.concurrent.TimeoutException -->主线程获取超时
        // Void aVoid = future.get(500L, TimeUnit.MILLISECONDS);

        // Exception in thread "main" java.util.concurrent.TimeoutException  -->主线程获取超时
        // Void aVoid = future.get(1500L, TimeUnit.MILLISECONDS);

        Void aVoid = future.get(2200L, TimeUnit.MILLISECONDS);// throws InterruptedException, ExecutionException, TimeoutException
        System.out.println(aVoid);// null
    }

}
